package readwritelock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁降级示例
 * <pre>
 *   锁降级指：写锁可以降级为读锁
 *   降级顺序为：获取写锁 -> 获取读锁 -> 释放写锁 -> 降级为读锁
 *   注意：写锁可降级为读锁，但读锁不能升级为写锁
 * </pre>
 *
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/09/12 上午 11:12
 */
public class LockDowngradingDemo {

    public static void main(String[] args) {
        ReadWriteLock readwritelock = new ReentrantReadWriteLock();
        //写线程
        new Thread(() -> {
            readwritelock.writeLock().lock();
            System.out.println(timeTag() + "写线程获得写锁");
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            readwritelock.readLock().lock();
            System.out.println(timeTag() + "写线程获取读锁");
            readwritelock.writeLock().unlock();
            System.out.println(timeTag() + "写线程释放写锁");
        }).start();
        //读线程
        new Thread(() -> {
            readwritelock.readLock().lock();
            System.out.println(timeTag() + "读线程获得读锁");
            readwritelock.readLock().unlock();
            System.out.println(timeTag() + "读线程释放读锁");
        }).start();

    }

    private static String timeTag() {
        return "[" + System.currentTimeMillis() + "]";
    }

}
